package com.krtech.wecard.config;

import cn.dev33.satoken.interceptor.SaAnnotationInterceptor;
import cn.hutool.core.util.StrUtil;
import com.krtech.wecard.framework.security.Inner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;

import java.io.File;

@Configuration
@Slf4j
public class WebMvcConfig implements WebMvcConfigurer {

    private final String BASE_PACKAGE = "com.krtech.wecard";
    private final String RESOURCE_PATTERN = "/**/*.class";

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("*")
                .maxAge(3600);
    }

    /**
     * 注册sa-token的拦截器，打开注解式鉴权功能 (如果您不需要此功能，可以删除此类)
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //扫描出所有包含有@Inner的接口
        ArrayList<String> stringList = new ArrayList<>();
        //spring工具类，可以获取指定路径下的全部类
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        try {
            String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                    ClassUtils.convertClassNameToResourcePath(BASE_PACKAGE) + RESOURCE_PATTERN;
            Resource[] resources = resourcePatternResolver.getResources(pattern);
            //MetadataReader 的工厂类
            MetadataReaderFactory readerfactory = new CachingMetadataReaderFactory(resourcePatternResolver);
            for (Resource resource : resources) {
                //用于读取类信息
                MetadataReader reader = readerfactory.getMetadataReader(resource);
                //扫描到的class
                String classname = reader.getClassMetadata().getClassName();
                Class<?> clazz = Class.forName(classname);

                String classAnnotationName = "";
                RequestMapping classRequestMapping = clazz.getAnnotation(RequestMapping.class);
                if (classRequestMapping != null){
                    String[] classAnnotation = classRequestMapping.value();
                    if (classAnnotation.length > 0){
                        classAnnotationName = classAnnotation[0];
                    }
                }


                Method[] declaredMethods = clazz.getDeclaredMethods();
                for (Method method:declaredMethods){
                    //判断是否有指定主解
                    Inner inner = method.getAnnotation(Inner.class);
                    if (inner != null) {
                        //将注解中的类型值作为key，对应的类作为 value
                        if (!inner.value()){
                            RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                            GetMapping getMapping = method.getAnnotation(GetMapping.class);
                            PostMapping postMapping = method.getAnnotation(PostMapping.class);
                            PutMapping putMapping = method.getAnnotation(PutMapping.class);
                            DeleteMapping deleteMapping = method.getAnnotation(DeleteMapping.class);

                            if (requestMapping != null){
                                String[] valueList = requestMapping.value();
                                for (String value:valueList){
                                    if (StrUtil.isNotEmpty(value)){
                                        String reqeustAnnotationName = classAnnotationName + value;
                                        stringList.add(reqeustAnnotationName);
                                    }
                                }
                            }else if (getMapping != null){
                                String[] valueList = getMapping.value();
                                for (String value:valueList){
                                    if (StrUtil.isNotEmpty(value)){
                                        String getAnnotationName = classAnnotationName + value;
                                        stringList.add(getAnnotationName);
                                    }
                                }
                            }else if (postMapping != null){
                                String[] valueList = postMapping.value();
                                for (String value:valueList){
                                    if (StrUtil.isNotEmpty(value)){
                                        String postAnnotationName = classAnnotationName + value;
                                        stringList.add(postAnnotationName);
                                    }
                                }
                            }else if (putMapping != null){
                                String[] valueList = putMapping.value();
                                for (String value:valueList){
                                    if (StrUtil.isNotEmpty(value)){
                                        String putAnnotationName = classAnnotationName + value;
                                        stringList.add(putAnnotationName);
                                    }
                                }
                            }else if (deleteMapping != null){
                                String[] valueList = deleteMapping.value();
                                for (String value:valueList){
                                    if (StrUtil.isNotEmpty(value)){
                                        String deleteAnnotationName = classAnnotationName + value;
                                        stringList.add(deleteAnnotationName);
                                    }
                                }
                            }

                        }
                    }
                }

            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        // 注册注解拦截器，并排除不需要注解鉴权的接口地址 (与登录拦截器无关)
//        stringList.add("/admin/**");
//        stringList.add("/admin/login.html");
        stringList.add("/swagger-resources/**");
        stringList.add("/api/v1/wxLogin");
        stringList.add("/api/v1/wxAdminLogin");
        stringList.add("/api/v1/wxPublicLogin");
        stringList.add("/api/v1/getPubliSigniture");
        stringList.add("/api/v1/wxPublicJudgeFocus");
        stringList.add("/api/v1/wxPublicGetWecard");
        stringList.add("/sys/user/**");
        stringList.add("/wx/portal/**");

//        stringList.add("/wx/menu/**");

//        stringList.add("/error");
//        stringList.add("/captcha");
//        stringList.add("/thumbnail");

        registry.addInterceptor(new SaAnnotationInterceptor()).addPathPatterns("/**")
                .excludePathPatterns(stringList);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        File file = new File("web");
        log.info(file.getAbsolutePath());
        registry.addResourceHandler("/admin/**")
                .addResourceLocations("file:" + file.getAbsolutePath() + "/admin/");
    }

}
